<template>
  <div class="app-container">

    <div class="page-content" style="display: flex;justify-content: center">
      <div style="position: absolute;left: 50px"><i class="el-icon-s-unfold"></i></div>
      <span>公告管理</span>
    </div>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
        >新增
        </el-button>
      </el-col>
    </el-row>

    <el-table v-loading="loading" :data="announcementList">
      <el-table-column label="主键" align="center" prop="id"/>
      <el-table-column label="标题" align="center" prop="title"/>
      <el-table-column label="内容" align="center" prop="content" width="180" show-overflow-tooltip/>
<!--      <el-table-column label="封面" align="center" prop="pic" width="180">
        <template slot-scope="scope">
          <div v-if="!scope.row.pic">暂无图像</div>
          <div v-else>
            <el-image
                style="width: 50px; height: 50px"
                :src="scope.row.pic"
                :preview-src-list="[scope.row.pic]">
            </el-image>
          </div>

        </template>
      </el-table-column>-->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
          >修改
          </el-button>
          <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
        background
        layout="total, sizes, prev, pager, next, jumper"
        :current-page="queryParams.pageNum"
        :page-size="queryParams.pageSize"
        :page-sizes="[10,20,50]"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handlePageChange"
    />

    <!-- 添加或修改公告管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="50%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="90px">
        <el-form-item label="标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入标题"/>
        </el-form-item>
        <quill-editor v-model="form.content" />
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listAnnouncement,
  getAnnouncement,
  delAnnouncement,
  addAnnouncement,
  updateAnnouncement
} from "@/api/project/announcement";
import { quillEditor } from 'vue-quill-editor'
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
export default {
  name: "Announcement",
  data() {
    return {
      loading: true,
      // 总条数
      total: 0,
      // 公告管理表格数据
      announcementList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        title: null,
        content: null,
        pic: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {}
    };
  },
  created() {
    this.getList();
  },
  components: {
    quillEditor
  },
  computed: {
    processedContent() {
      if (!this.postList.content) return "";
      // 使用 DOMParser 解析富文本内容
      const parser = new DOMParser();
      const doc = parser.parseFromString(this.postList.content, "text/html");

      // 修改 <p> 标签样式
      const paragraphs = doc.querySelectorAll("p");
      paragraphs.forEach((p) => {
        p.style.textIndent = "2em"; // 首行缩进
        p.style.lineHeight = "2.0"; // 行高
        p.style.margin = "10px 0"; // 上下边距
        p.style.padding = "0 10px"; // 上下边距
      });

      // 修改 <img> 标签样式
      const images = doc.querySelectorAll("img");
      images.forEach((img) => {
        img.style.width = "250px"; // 图片宽度
        img.style.height = "auto"; // 高度自适应
        img.style.borderRadius = "8px"; // 圆角
        img.style.margin = "10px 0"; // 上下边距
      });

      // 返回处理后的 HTML 内容
      return doc.body.innerHTML;
    },
  },
  methods: {
    getNow(){
      const now = new Date();

      const year = now.getFullYear();
      const month = String(now.getMonth() + 1).padStart(2, '0'); // 月份从0开始，需要加1
      const day = String(now.getDate()).padStart(2, '0');
      const hours = String(now.getHours()).padStart(2, '0');
      const minutes = String(now.getMinutes()).padStart(2, '0');
      const seconds = String(now.getSeconds()).padStart(2, '0');

      const formattedDate = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
      return formattedDate
    },
    handlePageChange(currentPage) {
      this.queryParams.pageNum = currentPage
      this.getList()
    },
    handleSizeChange(pageSize) {
      this.queryParams.pageSize = pageSize
      this.getList()
    },
    /** 查询公告管理列表 */
    getList() {
      this.loading = true;
      listAnnouncement(this.queryParams).then(response => {
        let list, start, end
        start = (this.queryParams.pageNum - 1) * this.queryParams.pageSize
        end = start + this.queryParams.pageSize
        list = response.data.filter((item, index) => {
          return index >= start && index < end
        })
        this.announcementList = list;
        this.total = response.data.length;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        title: null,
        content: null,
        createTime: null,
        pic: null
      };
      // this.resetForm("form");
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加公告管理";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      getAnnouncement(row).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改公告管理";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.form.createTime=this.getNow()
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateAnnouncement(this.form).then(response => {
              this.$message.success("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addAnnouncement(this.form).then(response => {
              this.$message.success("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$confirm('是否确认删除？').then(function () {
        return delAnnouncement(row);
      }).then(() => {
        this.getList();
        this.$message.success("删除成功");
      }).catch(() => {
      });
    },
  }
};
</script>
